<?php

namespace App\Models\Oauth;

use Illuminate\Support\Facades\DB;
use App\Models\Model;
use App\Models\Oauth\UserModel;
use App\Core\Utils\TwHelper\Environment;

/**
 * 登录日志
 */
class UserLoginLogModel extends Model
{

    const TABLENAME = 'tw_base_user_login_log';

    /**
     *
     * @global type 手机浏览器
     */
    const EQM_MOBILE = 1;

    /**
     *
     * @global type 通心粉pc客户端
     */
    const EQM_TXF_PC = 2;

    /**
     *
     * @global type 微信
     */
    const EQM_WX = 3;

    /**
     *
     * @global type pc浏览器
     */
    const EQM_PC = 4;

    /**
     *
     * @global type App(安卓)
     */
    const EQM_APP_ANDROID = 5;

    /**
     *
     * @global type App(苹果)
     */
    const EQM_APP_IOS = 6;

    /**
     *
     * @global type 新App(安卓)
     */
    const EQM_APPPRO_ANDROID = 11;

    /**
     *
     * @global type 新App(苹果)
     */
    const EQM_APPPRO_IOS = 12;

    /**
     *
     * @global type 登录
     */
    const TYPE_LOGIN = 1;

    /**
     *
     * @global type 退出
     */
    const TYPE_LOGIN_OUT = 2;

    /**
     * 初始化并返回数据库请求构建器
     *
     * @return Illuminate\Support\Facades\DB::table(TABLENAME)
     */
    public static function dbTable()
    {
        // return self::dbConnectionClub()->table(self::TABLE_NAME);
        return DB::table(self::TABLENAME);
    }

    public static function getEqmList()
    {
        return array(
            self::EQM_MOBILE,
            self::EQM_TXF_PC,
            self::EQM_WX,
            self::EQM_PC,
            self::EQM_APP_ANDROID,
            self::EQM_APP_IOS,
            self::EQM_APPPRO_ANDROID,
            self::EQM_APPPRO_IOS
        );
    }

    /**
     * 获取用户登录设备
     *
     * @return type
     */
    public static function getEqm()
    {
        if (Environment::isWeixin()) {
            return self::EQM_WX;
        }
        if (!Environment::isMobile()) {
            return self::EQM_PC;
        }
        return self::EQM_MOBILE;
    }

    /**
     * 记录日志
     * $type 1:登录，2:退出
     */
    public static function writeLog($type, $userId, $eqm = null)
    {
        $updateDate = $data = array();
        $data['type'] = $type;
        $data['user_id'] = $userId;
        $data['created'] = time();
        if ($type == self::TYPE_LOGIN) {
            $updateDate['last_login_time'] = time();
        } else {
            $updateDate['last_login_out_time'] = time();
        }
        $updateDate['last_login_ip'] = $data['ip'] = Environment::getRealIP();
        $updateDate['last_login_eqm'] = $data['eqm'] = $eqm ? $eqm : self::getEqm();
        //更新用户登录和退出的信息
        UserModel::updateUser($userId, $updateDate);
        //添加到日志表
        return self::dbTable()->insertGetId($data);
    }

    /**
     *
     */
    public static function getLastLoginInfo($where)
    {
        return self::dbTable()->select()->where($where)->orderBy('id','desc')->first();
    }

}

?>